#! /bin/bash

function extend_monitors() {

    case $1 in
        "right")
            xrandr --output $iScr --auto
            xrandr --output $eScr --auto --right-of $iScr
            xrandr --noprimary
        ;;

        "up")
            xrandr --output $iScr --auto
            xrandr --output $eScr --auto
            xrandr --output $iScr --auto --pos 0x1080 --output $eScr --auto --pos 0x0
            xrandr --noprimary
        ;;

        "left")
            xrandr --output $iScr --auto
            xrandr --output $eScr --auto --right-of $iScr
            xrandr --noprimary
        ;;
    esac
}

function laptop_monitor() {
    xrandr --output $iScr --auto --output $eScr --off
}

function external_monitor() {
    xrandr --output $eScr --auto --output $iScr --off
}

function mirror() {
    kill -9 $(pidof polybar)
}

function zenu() {
    echo $(\
        zenity --title='Screen options' --width 320 --height 320 --list\
            --column='Option' --column='Describe'\
            laptop       eDP                 \
            external     HDMI                \
            extend-left  'eDP left of  HDMI' \
            extend-right 'eDP right of HDMI' \
            extend-up    'eDP below of HDMI' \
            mirror       mirror \
    )
}

function hdmi_connect() {
    return $(xrandr | grep "$eScr connected")
}

if ! $([ -e $Dcache ] && [ -f $Dfile ])
then
    mkdir -p $Dcache
    echo false > $Dfile
    exit
fi

menu=$(zenu)

case $menu in
    ""|"?"|"--help"|"-h")
        echo -ne "\
--extend \t \t setup two monitors: external right of internal\n\
--laptop \t \t off external monitor\n\
--external \t \t off internal monitor and on external\n\n"
    ;;

    "extend-right")
        if [ hdmi_connect ]; then extend_monitors "right"; fi
    ;;

    "extend-up")
        if [ hdmi_connect ]; then extend_monitors "up"; fi
    ;;

    "extend-left")
        if [ hdmi_connect ]; then extend_monitors "left"; fi
    ;;

    "laptop") laptop_monitor ;;

    "external")
        if [ hdmi_connect ]; then external_monitor
        else echo There is no extend monitor; fi
    ;;

    "mirror") if [ hdmi_connect ]; then mirror; fi;;
esac
